package hong.jun.pet_home.Interceptor;

import hong.jun.basic.util.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(HandlerInterceptor.class);
    /**
     * 前置拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("请求-------" + request.getRequestURI());
        //获取请求头
        String uri = request.getRequestURI().split("/")[1];
        //放行特定字段
        if (null != uri) {
            return true;
        }
        //获取请求头里的U-TOKEN
        String uToken = request.getHeader("U-TOKEN");
        if (uToken != null) { //判断有没有U-TOKEN
            String userToken = RedisUtils.INSTANCE.get(uToken);//根据U-TOKEN
            if (!StringUtils.isBlank(userToken))//
                return true;
            //有U-TOKEN且redis比对成功 放行
            //U-TOKEN比对失败
            writeNoUserError(response);
            return false;
        } else {
            //请求头没有U-TOKEN
            writeNoUserError(response);
            return false;
        }
    }

    private void writeNoUserError(HttpServletResponse response) {
        PrintWriter writer = null;
        try {
            response.setCharacterEncoding("utf-8"); //返回编码格式
            response.setContentType("application/json; charset=utf-8"); // json方式放回
            writer = response.getWriter();
            writer.write("{\"success\":false,\"message\":\"noUser\"}");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
